﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace blackhouse.WebNemo.Business.Groups {
    public abstract class RecordFileOperation {

        #region Instance

        private static Func<IGroupRecord, string, RecordFileOperation> initialize;

        public static RecordFileOperation Get(IGroupRecord record, string column) {
            if (initialize == null) {
                Type t = GetRecordFileOperationType();
                ConstructorInfo ci = t.GetConstructor(new Type[] { typeof(IGroupRecord), typeof(string) });
                ParameterExpression pGroupRecord = Expression.Parameter(typeof(IGroupRecord));
                ParameterExpression pString = Expression.Parameter(typeof(String));
                //ParameterExpression pRecordFileOperation = Expression.Parameter(typeof(RecordFileOperation));
                initialize = Expression.Lambda<Func<IGroupRecord, string, RecordFileOperation>>(Expression.New(ci, pGroupRecord, pString), pGroupRecord, pString).Compile();
                //initialize = Expression.Lambda<Func<IGroupRecord, string, RecordFileOperation>>(Expression.New(ci, Expression.Parameter(typeof(IGroupRecord)), Expression.Parameter(typeof(string))),).Compile();
            }
            return initialize(record, column);
        }

        private static Type GetRecordFileOperationType() {
            string st = ConfigurationManager.AppSettings["RecordFileOperation"];
            Type t = typeof(NemoRecordFileOperation);
            if (!String.IsNullOrEmpty(st))
                t = Type.GetType(st, false);
            return t;
        }

        #endregion

        #region Fields

        protected IGroupRecord record;
        protected string column;

        #endregion

        #region Constructors

        public RecordFileOperation(IGroupRecord record, string column) {
            this.record = record;
            this.column = column;
        }

        #endregion

        #region Methods

        public abstract bool SaveFile(RecordFileData data, Stream fileStream);

        public abstract RecordFileData GetInfo();

        public abstract byte[] GetFileData();

        #endregion

    }
}
